package cn.com.twoke.game.client.handler;

import cn.com.twoke.game.client.GameClientManager;
import cn.com.twoke.game.client.cache.ClientCacheManager;
import cn.com.twoke.game.client.ui.UiManager;
import cn.com.twoke.game.common.entity.message.InviteJoinGameMessage;
import cn.com.twoke.game.common.handler.MessageHandler;
import javax.swing.*;
import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class InviteJoinGameMessageHandler implements MessageHandler<InviteJoinGameMessage> {
    @Override
    public void handle(Selector selector, SocketChannel channel, InviteJoinGameMessage message) throws IOException {
        if (message.getInviteType() == InviteJoinGameMessage.Type.INVITE) {
            int result = JOptionPane.showConfirmDialog(
                    UiManager.WINDOW,
                    "邀请您组队匹配 【" + message.getGameTitle() + "】",
                    "【"+message.getRoomMasterId()+"】 来自在线用户",
                    JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (result == JOptionPane.OK_OPTION) {
                message.setInviteType(InviteJoinGameMessage.Type.ACCEPT);
                message.setInviteUserId(ClientCacheManager.INSTANCE.getUsername());
            } else {
                message.setInviteType(InviteJoinGameMessage.Type.REJECT);
            }
            GameClientManager.INSTANCE.dealInviteJoinGame(message);
        } else if (message.getInviteType() == InviteJoinGameMessage.Type.ACCEPT) {
            if (ClientCacheManager.INSTANCE.getUsername().equals(message.getRoomMasterId())) { // 游戏房主操作
                UiManager.WINDOW.addPlayer(message.getInviteUserId());
            } else {
                UiManager.WINDOW.toGameRoom(message);
            }
        } else if (message.getInviteType() == InviteJoinGameMessage.Type.REJECT) {
            if (ClientCacheManager.INSTANCE.getUsername().equals(message.getRoomMasterId())) { // 游戏房主操作
                JOptionPane.showConfirmDialog(UiManager.WINDOW,
                        "用户 【" +message.getInviteUserId()+ "】 拒绝了邀请","提示",
                        JOptionPane.YES_NO_OPTION);
            }
        }
    }
}
